<template>
  <div class="better-calendar-container">
    <el-row :gutter="20">
      <!-- 左侧筛选面板 -->
      <el-col :span="6">
        <div class="filter-panel">
          <div class="panel-header">
            <h3>请选择日历类型</h3>
            <el-button 
              type="primary" 
              size="small" 
              @click="showTypeManage"
            >
              管理类型
            </el-button>
          </div>
          <div class="filter-list">
            <div v-for="(item, index) in filterItems" :key="index" class="filter-item">
              <el-checkbox v-model="item.checked" :style="{ color: item.color }">
                {{ item.label }}
              </el-checkbox>
              <div class="color-block" :style="{ backgroundColor: item.color }"></div>
            </div>
          </div>
          <el-button type="primary" class="filter-button" @click="applyFilters">确定</el-button>
        </div>
      </el-col>

      <!-- 右侧日历主体 -->
      <el-col :span="18">
        <div class="calendar-main">
          <div class="calendar-header">
            <div class="header-left">
              <el-button-group>
                <el-button @click="prevMonth">
                  <el-icon><ArrowLeft /></el-icon>
                </el-button>
                <el-button @click="nextMonth">
                  <el-icon><ArrowRight /></el-icon>
                </el-button>
              </el-button-group>
              <el-button @click="goToday" class="today-btn">今天</el-button>
            </div>
            <h2 class="current-date">{{ currentYear }}年 {{ currentMonth }}月</h2>
            <div class="header-right">
              <el-button type="primary" @click="addNewEvent" class="add-event-btn">
                <el-icon><Plus /></el-icon>
                添加事件
              </el-button>
            </div>
          </div>

          <!-- 加载指示器 -->
          <div v-if="loading" class="calendar-loading">
            <el-icon class="loading-icon"><Loading /></el-icon>
            <span>加载中...</span>
          </div>

          <!-- v-calendar 日历组件 -->
          <Calendar
            ref="calendar"
            :attributes="calendarAttributes"
            :from-page="{ month: currentMonth, year: currentYear }"
            :min-date="null"
            :max-date="null"
            :first-day-of-week="1"
            :masks="{
              weekdays: 'WW',
              title: 'YYYY年MM月',
              dayPopover: 'YYYY年MM月DD日'
            }"
            :locale="'zh-CN'"
            :theme-styles="{
              wrapper: {
                backgroundColor: 'white',
                border: '1px solid #ebeef5',
                borderRadius: '12px',
                boxShadow: '0 2px 12px rgba(0, 0, 0, 0.05)'
              },
              dayCell: {
                border: '1px solid #f0f0f0'
              },
              dayCellContent: {
                fontWeight: '500'
              }
            }"
            class="custom-calendar"
            @dayclick="handleDateClick"
            @update:from-page="handlePageChange"
          >
            <template #day-content="{ day, attributes }">
              <div class="custom-day-content">
                <div class="day-header">
                  <span class="day-number" :class="{ 'is-today': isToday(day.date) }">
                    {{ day.day }}
                  </span>
                  <span v-if="getLunarInfo(day.date)" class="lunar-date">{{ getLunarInfo(day.date) }}</span>
                  <span v-if="isHoliday(day.date)" class="holiday-tag">{{ getHolidayName(day.date) }}</span>
                </div>
                <div class="day-events">
                  <div 
                    v-for="attr in attributes.filter(a => a.customData)" 
                    :key="attr.key"
                    class="day-event"
                    :class="{
                      'event-start': attr.customData?.isStart,
                      'event-middle': attr.customData?.isContinuous && !attr.customData?.isStart && !attr.customData?.isEnd,
                      'event-end': attr.customData?.isEnd,
                      'single-day': !attr.customData?.isContinuous
                    }"
                    :style="{
                      backgroundColor: attr.customData?.color,
                      opacity: attr.customData?.isStart || !attr.customData?.isContinuous ? 1 : 0.9
                    }"
                    @click.stop="handleEventClick(attr.customData)"
                  >
                    <div class="event-content">
                      <span v-if="attr.customData?.isStart || !attr.customData?.isContinuous" class="event-title">
                        {{ attr.customData?.content }}
                      </span>
                      <span v-if="attr.customData?.isStart && attr.customData?.isContinuous" class="event-duration">
                        {{ attr.customData?.dayCount }}天
                      </span>
                    </div>
                  </div>
                </div>
                <div v-if="!isCurrentMonth(day.date)" class="not-current-month-overlay"></div>
              </div>
            </template>
          </Calendar>
          
          <!-- 日历底部图例说明 -->
          <div class="calendar-legend">
            <div class="legend-item">
              <div class="legend-color" style="background-color: rgba(0, 122, 255, 0.1);"></div>
              <span>今日</span>
            </div>
            <div class="legend-item">
              <div class="legend-color" style="background-color: rgba(255, 59, 48, 0.1);"></div>
              <span>节假日</span>
            </div>
            <div class="legend-item">
              <div class="legend-color" style="background-color: #f9f9f9;"></div>
              <span>周末</span>
            </div>
            <div class="legend-item">
              <div class="legend-color holiday-tag-sample">休</div>
              <span>法定假日</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 新增/编辑事件对话框 -->
    <el-dialog 
      :title="dialogType === 'add' ? '新增事件' : '编辑事件'"
      v-model="dialogVisible"
      width="500px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <el-form ref="eventFormRef" :model="eventForm" :rules="eventRules" label-width="80px" class="event-form">
        <el-form-item label="时间段" required>
          <el-row :gutter="10">
            <el-col :span="11">
              <el-form-item prop="start_date" class="date-form-item">
                <el-date-picker 
                  v-model="eventForm.start_date"
                  type="date"
                  placeholder="开始日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  class="date-picker"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2" class="text-center">至</el-col>
            <el-col :span="11">
              <el-form-item prop="end_date" class="date-form-item">
                <el-date-picker 
                  v-model="eventForm.end_date"
                  type="date"
                  placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :disabled-date="disableEndDate"
                  class="date-picker"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select 
            v-model="eventForm.type" 
            placeholder="选择事件类型" 
            @change="handleTypeChange"
            class="type-select"
          >
            <el-option 
              v-for="item in filterItems"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            >
              <div class="type-option">
                <span>{{ item.label }}</span>
                <div class="type-color" :style="{ backgroundColor: item.color }"></div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <div class="color-picker-wrapper">
            <el-color-picker 
              v-model="eventForm.color" 
              show-alpha
              :predefine="predefineColors"
              class="color-picker"
            />
            <span class="color-value">{{ eventForm.color }}</span>
          </div>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="eventForm.content" 
            type="textarea" 
            :rows="3"
            placeholder="请输入事件内容"
            class="content-textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitEvent" class="submit-btn">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 类型管理对话框 -->
    <el-dialog
      title="管理事件类型"
      v-model="typeDialogVisible"
      width="600px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div class="type-manage-header">
        <el-button type="primary" @click="handleAddType" class="add-type-btn">
          <el-icon><Plus /></el-icon>
          添加类型
        </el-button>
      </div>
      
      <el-table 
        :data="filterItems" 
        style="width: 100%"
        :header-cell-style="{
          backgroundColor: '#f5f7fa',
          color: '#333',
          fontWeight: '600'
        }"
        :row-class-name="() => 'type-table-row'"
      >
        <el-table-column prop="label" label="类型名称" width="180">
          <template #default="{ row }">
            <template v-if="row.editing">
              <el-input v-model="row.label" size="default" placeholder="输入类型名称" />
            </template>
            <span v-else class="type-name">{{ row.label }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="color" label="颜色" width="180">
          <template #default="{ row }">
            <template v-if="row.editing">
              <el-color-picker v-model="row.color" size="default" show-alpha :predefine="predefineColors" />
            </template>
            <div v-else class="color-preview" :style="{ backgroundColor: row.color }">
              {{ row.color }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作">
          <template #default="{ row }">
            <template v-if="row.editing">
              <el-button link type="primary" @click="handleSaveType(row)" class="action-btn">
                <el-icon><Check /></el-icon> 保存
              </el-button>
              <el-button link type="info" @click="handleCancelEdit(row)" class="action-btn">
                <el-icon><Close /></el-icon> 取消
              </el-button>
            </template>
            <template v-else>
              <el-button link type="primary" @click="handleEditType(row)" class="action-btn">
                <el-icon><Edit /></el-icon> 编辑
              </el-button>
              <el-button link type="danger" @click="handleDeleteType(row)" class="action-btn">
                <el-icon><Delete /></el-icon> 删除
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="typeDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue';
import { ArrowLeft, ArrowRight, Plus, Check, Close, Edit, Delete, Loading } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from '@/utils/http';

// 导入 v-calendar 组件
import { Calendar } from 'v-calendar';
import 'v-calendar/style.css';

const currentYear = ref(new Date().getFullYear());
const currentMonth = ref(new Date().getMonth() + 1);
const events = ref([]);
const filterItems = ref([]);

// 日历组件引用
const calendar = ref(null);

// 状态管理
const dialogVisible = ref(false);
const dialogType = ref('add');
const selectedEvent = ref(null);
const eventFormRef = ref(null);
const typeDialogVisible = ref(false);
const typeBeforeEdit = ref({});

// 节假日数据 (示例数据，实际应用中可从API获取)
const holidays = reactive({
  '2023-01-01': { name: '元旦', isHoliday: true },
  '2023-01-21': { name: '除夕', isHoliday: true },
  '2023-01-22': { name: '春节', isHoliday: true },
  '2023-01-23': { name: '春节假期', isHoliday: true },
  '2023-01-24': { name: '春节假期', isHoliday: true },
  '2023-04-05': { name: '清明节', isHoliday: true },
  '2023-05-01': { name: '劳动节', isHoliday: true },
  '2023-05-02': { name: '劳动节假期', isHoliday: true },
  '2023-05-03': { name: '劳动节假期', isHoliday: true },
  '2023-06-22': { name: '端午节', isHoliday: true },
  '2023-09-29': { name: '中秋节', isHoliday: true },
  '2023-10-01': { name: '国庆节', isHoliday: true },
  '2023-10-02': { name: '国庆节假期', isHoliday: true },
  '2023-10-03': { name: '国庆节假期', isHoliday: true },
  '2023-10-04': { name: '国庆节假期', isHoliday: true },
  '2023-10-05': { name: '国庆节假期', isHoliday: true },
  '2023-10-06': { name: '国庆节假期', isHoliday: true },
  
  // 2024年节假日
  '2024-01-01': { name: '元旦', isHoliday: true },
  '2024-02-10': { name: '除夕', isHoliday: true },
  '2024-02-11': { name: '春节', isHoliday: true },
  '2024-02-12': { name: '春节假期', isHoliday: true },
  '2024-02-13': { name: '春节假期', isHoliday: true },
  '2024-02-14': { name: '春节假期', isHoliday: true },
  '2024-02-15': { name: '春节假期', isHoliday: true },
  '2024-02-16': { name: '春节假期', isHoliday: true },
  '2024-02-17': { name: '春节假期', isHoliday: true },
  '2024-04-04': { name: '清明节', isHoliday: true },
  '2024-05-01': { name: '劳动节', isHoliday: true },
  '2024-05-02': { name: '劳动节假期', isHoliday: true },
  '2024-05-03': { name: '劳动节假期', isHoliday: true },
  '2024-05-04': { name: '劳动节假期', isHoliday: true },
  '2024-05-05': { name: '劳动节假期', isHoliday: true },
  '2024-06-10': { name: '端午节', isHoliday: true },
  '2024-09-17': { name: '中秋节', isHoliday: true },
  '2024-10-01': { name: '国庆节', isHoliday: true },
  '2024-10-02': { name: '国庆节假期', isHoliday: true },
  '2024-10-03': { name: '国庆节假期', isHoliday: true },
  '2024-10-04': { name: '国庆节假期', isHoliday: true },
  '2024-10-05': { name: '国庆节假期', isHoliday: true },
  '2024-10-06': { name: '国庆节假期', isHoliday: true },
  '2024-10-07': { name: '国庆节假期', isHoliday: true },
});

// 农历数据 (简化版，实际应用中可使用专门的农历库)
const lunarInfo = [
  0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,
  0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977,
  0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970,
  0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950,
  0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557
];

// 农历月份名称
const lunarMonths = ['正', '二', '三', '四', '五', '六', '七', '八', '九', '十', '冬', '腊'];

// 农历日期名称
const lunarDays = [
  '初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十',
  '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十',
  '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十'
];

// 获取农历信息
const getLunarInfo = (date) => {
  // 简化版农历计算，仅显示部分特殊日期
  // 实际应用中应使用专业农历库
  const formattedDate = formatDate(date);
  
  // 春节
  if (formattedDate === '2024-02-10') return '除夕';
  if (formattedDate === '2024-02-11') return '正月初一';
  if (formattedDate === '2024-02-12') return '正月初二';
  
  // 元宵节
  if (formattedDate === '2024-02-24') return '元宵节';
  
  // 端午节
  if (formattedDate === '2024-06-10') return '端午节';
  
  // 中秋节
  if (formattedDate === '2024-09-17') return '中秋节';
  
  // 重要节气
  if (formattedDate === '2024-04-04') return '清明';
  if (formattedDate === '2024-06-21') return '夏至';
  if (formattedDate === '2024-12-21') return '冬至';
  
  // 对于当前月份的日期，随机返回一些农历日期（仅作演示）
  if (isCurrentMonth(date)) {
    const day = date.getDate();
    if (day % 5 === 1) return lunarDays[day % 30];
  }
  
  return '';
};

// 判断是否是节假日
const isHoliday = (date) => {
  const formattedDate = formatDate(date);
  return holidays[formattedDate] !== undefined;
};

// 获取节假日名称
const getHolidayName = (date) => {
  const formattedDate = formatDate(date);
  return holidays[formattedDate]?.name || '';
};

// 判断是否是当前月份
const isCurrentMonth = (date) => {
  return date.getMonth() + 1 === currentMonth.value && 
         date.getFullYear() === currentYear.value;
};

// 添加新事件
const addNewEvent = () => {
  dialogType.value = 'add';
  selectedEvent.value = null;
  const today = new Date();
  const formattedDate = formatDate(today);
  eventForm.value = {
    start_date: formattedDate,
    end_date: formattedDate,
    type: filterItems.value.length > 0 ? filterItems.value[0].label : '',
    content: '',
    color: filterItems.value.length > 0 ? filterItems.value[0].color : '#007aff'
  };
  dialogVisible.value = true;
};

const eventForm = ref({
  start_date: '',
  end_date: '',
  content: '',
  type: '',
  color: null
});

const eventRules = {
  start_date: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  end_date: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  type: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入事件内容', trigger: 'blur' }]
};

// 禁用结束日期早于开始日期
const disableEndDate = (date) => {
  if (!eventForm.value.start_date) return false;
  return date < new Date(eventForm.value.start_date);
};

// 判断是否是今天
const isToday = (date) => {
  const today = new Date();
  return date.getDate() === today.getDate() &&
         date.getMonth() === today.getMonth() &&
         date.getFullYear() === today.getFullYear();
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  
  if (typeof date === 'string') {
    // 如果已经是YYYY-MM-DD格式，直接返回
    if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
      return date;
    }
    date = new Date(date);
  }
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 添加加载状态
const loading = ref(false);

// 获取事件数据
const fetchEvents = async () => {
  loading.value = true;
  
  try {
    // 添加防御性检查
    const checkedFilters = filterItems.value?.filter(item => item?.checked)?.map(item => item?.label) || [];
    
    console.log('获取事件数据:', {
      year: currentYear.value,
      month: currentMonth.value,
      filter: checkedFilters // 直接使用数组
    });

    // 手动构建 URL 参数，避免 axios 自动将数组转换为 filter[]=xxx 格式
    let url = `/calendar/events?year=${currentYear.value}&month=${currentMonth.value}`;
    
    // 为每个筛选条件添加 &filter=xxx 参数
    if (checkedFilters.length > 0) {
      checkedFilters.forEach(filter => {
        url += `&filter=${encodeURIComponent(filter)}`;
      });
    }
    
    console.log('请求 URL:', url);
    const data = await http.get(url);
    
    console.log('获取到的事件数据:', data);
    
    if (data && Array.isArray(data)) {
      events.value = data;
    } else if (data && typeof data === 'object' && Array.isArray(data.data)) {
      events.value = data.data;
    } else {
      console.warn('事件数据格式不正确:', data);
      events.value = [];
    }
    
    if(!events.value.length) {
      ElMessage.info('当前月份暂无事件数据');
    }
  } catch (error) {
    console.error('获取事件失败:', error);
    ElMessage.error(error.message || '获取事件失败');
    events.value = []; // 确保错误时设置为空数组
  } finally {
    loading.value = false;
  }
};

// 处理页面变化
const handlePageChange = (page) => {
  if (!page || !page.year || !page.month) {
    console.warn('页面变化事件缺少必要参数:', page);
    return;
  }
  
  console.log('页面变化:', page);
  currentYear.value = page.year;
  currentMonth.value = page.month;
  fetchEvents();
};

// 处理日期点击
const handleDateClick = (day) => {
  dialogType.value = 'add';
  selectedEvent.value = null;
  const formattedDate = formatDate(day.date);
  eventForm.value = {
    start_date: formattedDate,
    end_date: formattedDate,
    type: '',
    content: '',
    color: ''
  };
  dialogVisible.value = true;
};

// 处理事件点击
const handleEventClick = (event) => {
  if (!event) return;
  
  dialogType.value = 'edit';
  selectedEvent.value = event;
  eventForm.value = { 
    ...event,
    start_date: event.start_date,
    end_date: event.end_date 
  };
  dialogVisible.value = true;
};

// 处理类型变化
const handleTypeChange = (type) => {
  const selectedType = filterItems.value.find(item => item.label === type);
  if (selectedType) {
    eventForm.value.color = selectedType.color;
  }
};

// 处理提交事件
const handleSubmitEvent = async () => {
  if (!eventFormRef.value) return;
  
  await eventFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          start_date: eventForm.value.start_date,
          end_date: eventForm.value.end_date,
          content: eventForm.value.content.trim().substring(0, 500),
          type: eventForm.value.type.trim().substring(0, 50),
          color: eventForm.value.color || null
        };

        if (dialogType.value === 'add') {
          await http.post('/calendar/events', submitData);
          ElMessage.success('添加成功');
        } else {
          submitData.id = selectedEvent.value.id;
          await http.put(`/calendar/events/${selectedEvent.value.id}`, submitData);
          ElMessage.success('更新成功');
        }
        
        dialogVisible.value = false;
        fetchEvents();
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error(error.message || '操作失败');
      }
    }
  });
};

// 导航方法
const prevMonth = () => {
  if (calendar.value) {
    const newMonth = currentMonth.value === 1 ? 12 : currentMonth.value - 1;
    const newYear = currentMonth.value === 1 ? currentYear.value - 1 : currentYear.value;
    currentMonth.value = newMonth;
    currentYear.value = newYear;
    fetchEvents();
  }
};

const nextMonth = () => {
  if (calendar.value) {
    const newMonth = currentMonth.value === 12 ? 1 : currentMonth.value + 1;
    const newYear = currentMonth.value === 12 ? currentYear.value + 1 : currentYear.value;
    currentMonth.value = newMonth;
    currentYear.value = newYear;
    fetchEvents();
  }
};

const goToday = () => {
  const today = new Date();
  currentYear.value = today.getFullYear();
  currentMonth.value = today.getMonth() + 1;
  fetchEvents();
};

// 应用筛选
const applyFilters = () => {
  fetchEvents();
};

// 获取日历类型
const fetchCalendarTypes = async () => {
  try {
    const data = await http.get('/calendar/types');
    // 确保data存在且为数组
    if (data && Array.isArray(data)) {
      filterItems.value = data.map(item => ({
        ...item,
        checked: true // 添加checked属性
      }));
    } else {
      filterItems.value = [
        { label: '请添加事件类型-1', checked: true, color: '#FF69B4' },
        { label: '请添加事件类型-2', checked: true, color: '#FFB6C1' },
        { label: '请添加事件类型-3', checked: true, color: '#FFD700' },
      ];
      ElMessage.info('使用默认日历类型数据');
    }
  } catch (error) {
    console.error('获取日历类型失败:', error);
    ElMessage.error(error.message || '获取日历类型失败');
    // 设置默认值
    filterItems.value = [
      { label: '新股上市', checked: true, color: '#FF69B4' },
      { label: '新股申购', checked: true, color: '#FFB6C1' },
      { label: '可转债', checked: true, color: '#FFD700' },
    ];
  }
};

// 类型管理方法
const showTypeManage = () => {
  typeDialogVisible.value = true;
};

const handleAddType = () => {
  const newType = {
    label: '新建类型',
    color: '#409EFF',
    checked: true,
    editing: true,
    isNew: true
  };
  filterItems.value.unshift(newType);
};

const handleEditType = (row) => {
  typeBeforeEdit.value = { ...row };
  row.editing = true;
};

const handleCancelEdit = (row) => {
  if (row.isNew) {
    filterItems.value = filterItems.value.filter(item => item !== row);
  } else {
    Object.assign(row, typeBeforeEdit.value);
    row.editing = false;
  }
};

const handleSaveType = async (row) => {
  try {
    if (row.isNew) {
      // 添加新类型
      const data = await http.post('/calendar/types', {
        label: row.label,
        color: row.color
      });
      row.id = data.id;
      row.isNew = false;
    } else {
      // 更新已有类型
      await http.put(`/calendar/types/${row.id}`, {
        label: row.label,
        color: row.color
      });
    }
    row.editing = false;
    ElMessage.success('保存成功');
  } catch (error) {
    ElMessage.error(error.message || '保存失败');
  }
};

const handleDeleteType = async (row) => {
  try {
    await ElMessageBox.confirm(
      '删除后相关事件的类型将被设为"其他"，是否继续？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await http.delete(`/calendar/types/${row.id}`);
    filterItems.value = filterItems.value.filter(item => item !== row);
    ElMessage.success('删除成功');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败');
    }
  }
};

// 预定义颜色
const predefineColors = [
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
  '#ff69b4'
];

// 计算日历属性
const calendarAttributes = computed(() => {
  const attributes = [];
  
  try {
    // 添加今天的标记
    const today = new Date();
    attributes.push({
      key: 'today',
      dates: today,
      highlight: {
        color: '#007aff',
        fillMode: 'solid',
        contentClass: 'today-highlight'
      },
      popover: {
        label: '今天'
      }
    });
    
    // 添加节假日标记
    Object.keys(holidays).forEach(dateStr => {
      try {
        const holiday = holidays[dateStr];
        const date = new Date(dateStr);
        
        // 只添加当前年月的节假日
        if (date.getFullYear() === currentYear.value && 
            date.getMonth() + 1 === currentMonth.value) {
          attributes.push({
            key: `holiday-${dateStr}`,
            dates: date,
            highlight: {
              color: '#ff3b30',
              fillMode: 'light',
              contentClass: 'holiday-highlight'
            },
            popover: {
              label: holiday.name
            }
          });
        }
      } catch (err) {
        console.error('处理节假日时出错:', err);
      }
    });
    
    // 添加事件标记
    if (events.value && events.value.length > 0) {
      const eventAttributes = events.value.flatMap(event => {
        try {
          if (!event || !event.start_date || !event.end_date) {
            console.warn('事件数据不完整:', event);
            return [];
          }
          
          // 确定事件是否跨天
          const isContinuous = event.start_date !== event.end_date;
          
          // 创建日期范围
          const startDate = new Date(event.start_date);
          const endDate = new Date(event.end_date);
          
          if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
            console.warn('事件日期无效:', event);
            return [];
          }
          
          // 为每一天创建一个属性
          const result = [];
          const currentDate = new Date(startDate);
          
          // 计算事件持续的天数
          const daysDiff = Math.round((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
          
          while (currentDate <= endDate) {
            const formattedDate = formatDate(currentDate);
            const isStart = formattedDate === event.start_date;
            const isEnd = formattedDate === event.end_date;
            
            // 为连续事件设置不同的样式
            let highlightClass = 'single-day';
            if (isContinuous) {
              if (isStart) highlightClass = 'event-start';
              else if (isEnd) highlightClass = 'event-end';
              else highlightClass = 'event-middle';
            }
            
            result.push({
              key: `${event.id || 'temp'}-${formattedDate}`,
              dates: new Date(currentDate),
              dot: false,
              highlight: {
                color: event.color || '#007aff',
                fillMode: 'light',
                contentClass: highlightClass
              },
              customData: {
                ...event,
                isStart,
                isEnd,
                isContinuous,
                formattedDate,
                dayCount: daysDiff
              },
              popover: {
                label: event.content || '未命名事件'
              }
            });
            
            // 移动到下一天
            currentDate.setDate(currentDate.getDate() + 1);
          }
          
          return result;
        } catch (error) {
          console.error('处理事件属性时出错:', error, event);
          return [];
        }
      });
      
      attributes.push(...eventAttributes);
    }
    
    return attributes;
  } catch (error) {
    console.error('生成日历属性时出错:', error);
    // 确保至少返回今天的标记
    const today = new Date();
    return [{
      key: 'today',
      dates: today,
      highlight: {
        color: '#007aff',
        fillMode: 'solid',
        contentClass: 'today-highlight'
      },
      popover: {
        label: '今天'
      }
    }];
  }
});

// 初始化
onMounted(async () => {
  await fetchCalendarTypes();
  await fetchEvents();
});
</script>

<style>
/* 添加页面切换动画 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.better-calendar-container {
  animation: fadeIn 0.5s ease-out;
  width: 100%;
  padding: 24px;
  box-sizing: border-box;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.filter-panel {
  background-color: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  height: 100%;
  border: 1px solid rgba(0, 0, 0, 0.03);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.panel-header h3 {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin: 0;
}

.filter-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
}

.filter-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border-radius: 8px;
  transition: background-color 0.3s ease;
}

.filter-item:hover {
  background-color: #f5f7fa;
}

.color-block {
  width: 18px;
  height: 18px;
  border-radius: 6px;
  margin-left: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.filter-button {
  width: 100%;
  margin-top: 24px;
  border-radius: 8px;
  height: 40px;
  font-weight: 500;
}

.calendar-main {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  padding: 24px;
  height: 100%;
  border: 1px solid rgba(0, 0, 0, 0.03);
  position: relative;
  min-height: 700px; /* 确保日历有最小高度 */
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-right {
  display: flex;
  align-items: center;
}

.add-event-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 16px;
  font-weight: 500;
  border-radius: 8px;
  background-color: #007aff;
  border-color: #007aff;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
}

.add-event-btn:hover {
  background-color: #0066cc;
  border-color: #0066cc;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.4);
}

.header-left .el-button-group .el-button {
  border-radius: 8px;
  height: 36px;
  width: 36px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.today-btn {
  border-radius: 8px;
  height: 36px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.current-date {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
  position: relative;
}

.current-date::after {
  content: '';
  position: absolute;
  bottom: -4px;
  left: 0;
  width: 40px;
  height: 2px;
  background-color: #007aff;
  border-radius: 2px;
}

/* 自定义 v-calendar 样式 */
.custom-calendar {
  --vc-font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
  --vc-text-sm: 14px;
  --vc-text-base: 14px;
  --vc-rounded-full: 50%;
  --vc-rounded-lg: 12px;
  --vc-gray-100: #f5f7fa;
  --vc-gray-200: #ebeef5;
  --vc-gray-300: #e4e7ed;
  --vc-gray-400: #c0c4cc;
  --vc-gray-500: #909399;
  --vc-gray-600: #606266;
  --vc-gray-700: #303133;
  --vc-gray-800: #1e1e1e;
  --vc-gray-900: #000000;
  --vc-blue-100: #ecf5ff;
  --vc-blue-200: #d9ecff;
  --vc-blue-300: #c6e2ff;
  --vc-blue-400: #a0cfff;
  --vc-blue-500: #007aff;
  --vc-blue-600: #0070e8;
  --vc-blue-700: #0064d2;
  --vc-blue-800: #0057b8;
  --vc-blue-900: #004a9f;
  width: 100%;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  background-color: white;
  transition: box-shadow 0.3s ease;
  min-height: 600px; /* 确保日历有最小高度 */
}

.custom-calendar:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
}

.vc-container {
  --day-content-height: 110px;
  width: 100%;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  min-height: 600px; /* 确保日历有最小高度 */
}

.custom-day-content {
  height: 100%;
  min-height: 110px;
  display: flex;
  flex-direction: column;
  position: relative;
  padding: 4px;
}

.day-header {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 4px;
  position: relative;
}

.day-number {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  margin-bottom: 2px;
  font-weight: 500;
}

.day-number.is-today {
  background-color: #007aff;
  color: white;
  border-radius: 50%;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
  animation: pulse 2s infinite;
}

.lunar-date {
  font-size: 10px;
  color: #909399;
  margin-top: 2px;
  display: block;
  text-align: center;
  line-height: 1.2;
}

.holiday-tag {
  position: absolute;
  top: 2px;
  right: 4px;
  font-size: 10px;
  color: #ff3b30;
  background-color: rgba(255, 59, 48, 0.1);
  padding: 1px 4px;
  border-radius: 4px;
  font-weight: 500;
  z-index: 2;
}

.day-events {
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
  position: relative;
  z-index: 5;
  min-height: 70px; /* 确保事件区域有最小高度 */
}

.not-current-month-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(250, 250, 250, 0.7);
  z-index: 4;
  backdrop-filter: blur(1px);
}

.day-event {
  font-size: 12px;
  padding: 4px 10px;
  color: white;
  border-radius: 8px;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-height: 24px;
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0.05);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  position: relative;
  z-index: 5;
  font-weight: 500;
  letter-spacing: 0.2px;
  transition: all 0.2s ease;
}

.day-event:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12);
}

.event-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.event-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.event-duration {
  font-size: 10px;
  background-color: rgba(255, 255, 255, 0.3);
  padding: 1px 6px;
  border-radius: 10px;
  margin-left: 6px;
  white-space: nowrap;
}

/* 优化连续事件的视觉效果 */
.day-event.event-start {
  border-radius: 8px 0 0 8px;
  border-right: none;
  padding-right: 12px;
  z-index: 10;
  margin-right: -2px; /* 确保连续性 */
  position: relative;
}

.day-event.event-start::after {
  content: '';
  position: absolute;
  top: 0;
  right: -2px;
  bottom: 0;
  width: 4px;
  background-color: inherit;
}

.day-event.event-middle {
  border-radius: 0;
  border-left: none;
  border-right: none;
  padding-left: 6px;
  padding-right: 6px;
  z-index: 9;
  margin-left: -2px; /* 确保连续性 */
  margin-right: -2px; /* 确保连续性 */
  position: relative;
}

.day-event.event-middle::before,
.day-event.event-middle::after {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: inherit;
}

.day-event.event-middle::before {
  left: -2px;
}

.day-event.event-middle::after {
  right: -2px;
}

.day-event.event-end {
  border-radius: 0 8px 8px 0;
  border-left: none;
  padding-left: 6px;
  z-index: 10;
  margin-left: -2px; /* 确保连续性 */
  position: relative;
}

.day-event.event-end::before {
  content: '';
  position: absolute;
  top: 0;
  left: -2px;
  bottom: 0;
  width: 4px;
  background-color: inherit;
}

.day-event.single-day {
  z-index: 10;
  border-radius: 8px;
}

/* 连续事件样式 */
.vc-day-layer .vc-highlight.event-start {
  border-radius: 8px 0 0 8px !important;
  margin-right: -1px;
}

.vc-day-layer .vc-highlight.event-middle {
  border-radius: 0 !important;
  margin-left: -1px;
  margin-right: -1px;
}

.vc-day-layer .vc-highlight.event-end {
  border-radius: 0 8px 8px 0 !important;
  margin-left: -1px;
}

.vc-day-layer .vc-highlight.single-day {
  border-radius: 8px !important;
}

/* 增强日历单元格的视觉效果 */
:deep(.vc-day) {
  background-color: white;
  border: 1px solid #f0f0f0;
  transition: all 0.2s ease;
  min-height: 120px; /* 确保日期单元格有最小高度 */
}

:deep(.vc-day:hover) {
  background-color: #f0f7ff;
  z-index: 2;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
}

:deep(.vc-day.is-today) {
  background-color: rgba(0, 122, 255, 0.05);
}

:deep(.vc-day.is-not-in-month) {
  background-color: #fafafa;
}

/* 增强周末的视觉区分 */
:deep(.vc-day.weekday-0),
:deep(.vc-day.weekday-6) {
  background-color: #f9f9f9;
}

/* 节假日和农历样式 */
.holiday-highlight {
  background-color: rgba(255, 59, 48, 0.1) !important;
  border: 1px dashed rgba(255, 59, 48, 0.3) !important;
}

.today-highlight {
  background-color: rgba(0, 122, 255, 0.1) !important;
  border: 1px solid rgba(0, 122, 255, 0.3) !important;
}

/* 优化日历图例 */
.calendar-legend {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 16px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.legend-item:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.holiday-tag-sample {
  font-size: 10px;
  color: #ff3b30;
  background-color: rgba(255, 59, 48, 0.1);
  padding: 1px 4px;
  border-radius: 4px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 优化日历周标题 */
:deep(.vc-weekday) {
  font-weight: 600;
  color: #606266;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

/* 优化日历日期内容 */
:deep(.vc-day-content) {
  font-weight: 500;
  height: 28px !important;
  margin: 2px 0 !important;
}

/* 添加一些微妙的动画效果 */
@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

/* 优化日历事件的显示 */
.day-event {
  position: relative;
  overflow: visible;
}

.day-event::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: inherit;
  filter: blur(6px);
  opacity: 0.4;
  z-index: -1;
  border-radius: inherit;
  transform: scale(1.05);
  pointer-events: none;
  transition: all 0.3s ease;
}

.day-event:hover::before {
  opacity: 0.6;
  transform: scale(1.1);
}

/* 优化按钮组 */
.header-left .el-button-group {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  transform: translateY(0);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

:deep(.el-dialog:hover) {
  box-shadow: 0 25px 70px rgba(0, 0, 0, 0.15);
}

:deep(.el-dialog__header) {
  padding: 20px 24px;
  margin: 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

:deep(.el-dialog__title) {
  font-weight: 600;
  font-size: 18px;
  color: #333;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-button-group .el-button:hover) {
  transform: translateY(-1px);
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 1px solid #e4e7ed;
}

:deep(.el-input__inner:focus),
:deep(.el-textarea__inner:focus) {
  border-color: #007aff;
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.2);
}

:deep(.el-input__inner:hover),
:deep(.el-textarea__inner:hover) {
  border-color: #c0c4cc;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-date-editor) {
  width: 100%;
  border-radius: 8px;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #007aff;
  border-color: #007aff;
}

:deep(.el-checkbox__inner) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-checkbox__inner:hover) {
  border-color: #007aff;
}

:deep(.el-color-picker__trigger) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-color-picker__trigger:hover) {
  transform: scale(1.05);
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

:deep(.el-table:hover) {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

:deep(.el-table__header-wrapper th) {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #333;
}

:deep(.el-table__row) {
  transition: background-color 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 文本居中样式 */
.text-center {
  text-align: center;
  line-height: 32px;
}

/* 颜色选择器样式 */
.color-picker-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
}

.color-value {
  color: #909399;
  font-size: 14px;
  background-color: #f5f7fa;
  padding: 4px 8px;
  border-radius: 4px;
  font-family: monospace;
}

/* 类型管理样式 */
.type-manage-header {
  margin-bottom: 24px;
  display: flex;
  justify-content: flex-end;
}

.type-name {
  font-weight: 500;
  color: #333;
}

.color-preview {
  display: inline-block;
  padding: 6px 12px;
  border-radius: 6px;
  color: #fff;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.action-btn {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.type-table-row {
  transition: background-color 0.3s ease;
}

.type-table-row:hover {
  background-color: #f8f8f8;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 8px;
}

/* 表单项样式 */
.el-form-item {
  margin-bottom: 24px;
}

/* 优化滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 增加响应式布局支持 */
@media (max-width: 768px) {
  .better-calendar-container {
    padding: 16px;
  }
  
  .filter-panel, .calendar-main {
    padding: 16px;
  }
  
  .current-date {
    font-size: 20px;
  }
  
  .calendar-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .header-right {
    width: 100%;
  }
  
  .add-event-btn {
    width: 100%;
  }
}

/* 加载指示器样式 */
.calendar-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 100;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 20px 30px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(4px);
}

.loading-icon {
  font-size: 24px;
  color: #007aff;
  animation: rotate 1.5s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style> 